package com.canal.admin.service.impl;

import com.canal.admin.dao.ZcolLoginRecordMapper;
import com.canal.admin.dao.ZcolRtDataMapper;
import com.canal.admin.dao.ZcolRtRegMapper;
import com.canal.admin.entity.data.ZcolLoginRecord;
import com.canal.admin.entity.data.ZcolRtReg;
import com.canal.admin.service.RtDataService;
import com.canal.admin.transfer.req.data.RtConvertConditions;
import com.canal.admin.transfer.req.data.RtDataConditions;
import com.canal.admin.transfer.req.data.RtDataDetailConditions;
import com.canal.admin.transfer.resp.PageResp;
import com.canal.admin.transfer.resp.rt.CanalUvIncome;
import com.canal.admin.transfer.resp.rt.RtConvertResp;
import com.canal.admin.transfer.resp.rt.RtDataResp;
import com.canal.admin.transfer.resp.rt.RtDetailResp;
import com.canal.admin.util.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yangbo
 * @date 2020-07-14 9:30
 */
@Service
@Slf4j
public class RtDataServiceImpl implements RtDataService {


    @Autowired
    private ZcolRtDataMapper zcolRtDataMapper;

    @Autowired
    private ZcolRtRegMapper zcolRtRegMapper;

    @Autowired
    private ZcolLoginRecordMapper zcolLoginRecordMapper;

    /**
     * 实时统计数据
     * @param conditions
     * @return
     */
    @Override
    public PageResp<RtDataResp> rtDataList(RtDataConditions conditions) {
        PageHelper.startPage(conditions.getPageNo(),conditions.getPageSize());
        List<RtDataResp> rtDataRespList = zcolRtDataMapper.rtDataList(conditions);
        PageInfo<RtDataResp> pageInfo = new PageInfo<>(rtDataRespList);
        PageResp<RtDataResp> pageResp = PageUtil.toResp(pageInfo);
        List<RtDataResp> dataRespList = pageResp.getDataList();
        List<RtDataResp> rtDataResps = new ArrayList<>(dataRespList.size() + 1);
        for (RtDataResp rtDataResp : dataRespList) {
            //计算注册数
            List<ZcolRtReg> rtRegList = zcolRtRegMapper.rtRegByChannelIp(rtDataResp.getCiid(),rtDataResp.getIp());
            rtDataResp.setRegCount(rtRegList.size());
            List<String> phoneList = rtRegList.stream().map(ZcolRtReg::getPhone).collect(Collectors.toList());
            rtDataResp.setPhoneList(phoneList);
            rtDataResp.setIsLogin(false);
            if(!rtRegList.isEmpty()) {
                for (ZcolRtReg zcolRtReg : rtRegList) {
                    Boolean reged = zcolRtReg.getReged();
                    if(reged) {
                        rtDataResp.setIsLogin(reged);
                        break;
                    }
                }
            }
            rtDataResps.add(rtDataResp);
        }
        pageResp.setDataList(rtDataResps);
        return pageResp;
    }

    /**
     * 实时访问明细
     * @param conditions
     * @return
     */
    @Override
    public PageResp<RtDetailResp> rtDetailList(RtDataDetailConditions conditions) {
        PageHelper.startPage(conditions.getPageNo(),conditions.getPageSize());
        List<RtDetailResp> rtDetailRespList = zcolRtDataMapper.rtDetailList(conditions);
        PageInfo<RtDetailResp> pageInfo = new PageInfo<>(rtDetailRespList);
        return PageUtil.toResp(pageInfo);
    }

    /**
     * 实时转化
     * @param conditions
     * @return
     */
    @Override
    public PageResp rtConvertList(RtConvertConditions conditions) {
        PageHelper.startPage(conditions.getPageNo(),conditions.getPageSize());
        conditions.setDiffDate(0);
        List<RtConvertResp> convertRespList = zcolRtDataMapper.rtConvertList(conditions);
        PageInfo<RtConvertResp> pageInfo = new PageInfo<>(convertRespList);
        PageResp<RtConvertResp> pageResp = PageUtil.toResp(pageInfo);
        List<RtConvertResp> convertResps = pageResp.getDataList();
        List<CanalUvIncome> uvIncomeList = new ArrayList<>();
        if(!convertResps.isEmpty()) {
            List<String> canals = convertResps.stream().map(RtConvertResp::getItemName)
                    .distinct().collect(Collectors.toList());
            uvIncomeList = zcolRtDataMapper.canalIncome(canals,0);
        }
        List<RtConvertResp> resultConvertList = new ArrayList<>(convertResps.size() + 1);
        for (RtConvertResp convert : convertResps) {
            BigDecimal uvCostAmount = convert.getUvPrice().multiply(new BigDecimal(convert.getUv()))
                    .setScale(2, RoundingMode.HALF_DOWN);
            List<ZcolRtReg> zcolRtRegList = zcolRtRegMapper.rtRegByChannel(convert.getCiid(),conditions.getDiffDate());
            int regCount = zcolRtRegList.size();
            BigDecimal regCostAmount = convert.getRegPrice().multiply(new BigDecimal(regCount));
            List<String> phones = zcolRtRegList.stream().map(ZcolRtReg::getPhone).collect(Collectors.toList());
            int loginCount = 0;
            if(!phones.isEmpty()) {
                loginCount = zcolLoginRecordMapper.loginCount(convert.getCiid(),phones);
            }
            BigDecimal regRate = new BigDecimal(regCount)
                    .divide(new BigDecimal(convert.getUv()),4,RoundingMode.HALF_DOWN)
                    .multiply(new BigDecimal(100)).setScale(2,RoundingMode.HALF_DOWN);
            BigDecimal loginRate;
            if(regCount > 0) {
                loginRate = new BigDecimal(loginCount)
                        .divide(new BigDecimal(regCount),4,RoundingMode.HALF_DOWN)
                        .multiply(new BigDecimal(100)).setScale(2,RoundingMode.HALF_DOWN);
            } else {
                loginRate = BigDecimal.ZERO;
            }
            convert.setUvCostAmount(uvCostAmount);
            convert.setRegCount(regCount);
            convert.setRegCostAmount(regCostAmount);
            convert.setLoginCount(loginCount);
            convert.setRegRate(regRate);
            convert.setLoginRate(loginRate);
            //获取商家信息并计算毛利
            CanalUvIncome canalUvIncome = getItem(uvIncomeList,convert.getItemName());
            if(canalUvIncome != null) {
                convert.setCanalUv(canalUvIncome.getCanalUv());
                convert.setIncomeAmount(canalUvIncome.getIncomeAmount());
                BigDecimal avgUv = new BigDecimal(canalUvIncome.getCanalUv())
                        .divide(new BigDecimal(convert.getUv()),4,RoundingMode.HALF_DOWN);
                convert.setAvgUv(avgUv);
                BigDecimal profit = canalUvIncome.getIncomeAmount().subtract(regCostAmount);
                convert.setProfit(profit);
            } else {
                convert.setCanalUv(0);
                convert.setIncomeAmount(BigDecimal.ZERO);
                convert.setAvgUv(BigDecimal.ZERO);
                convert.setProfit(BigDecimal.ZERO.subtract(regCostAmount));
            }
            resultConvertList.add(convert);
        }
        pageResp.setDataList(resultConvertList);
        return pageResp;
    }

    /**
     * 得到匹配的商家信息
     * @param uvIncomeList
     * @param itemName
     * @return
     */
    private CanalUvIncome getItem(List<CanalUvIncome> uvIncomeList,String itemName) {
        List<CanalUvIncome> items = uvIncomeList.stream().filter(item -> itemName.equals(item.getCanal()))
                .collect(Collectors.toList());
        if(items.isEmpty()) {
            return null;
        }
        return items.get(0);
    }
}
